package com.example;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

import com.example.dao.UserDao;
import com.example.pojo.User;
import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.binding.MapperProxy;
import org.apache.ibatis.binding.MapperProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.SqlSessionManager;


public class MyBatisTest {

    public static void main(String[] args) {
       a();
    }

    public static void a (){
        try {
            //读取mybatis-config.xml文件
            InputStream resourceAsStream = Resources.getResourceAsStream("MapperConfig.xml");
            //初始化mybatis,创建SqlSessionFactory类的实例
            SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建session实例
            SqlSession session = sqlSessionFactory.openSession();
//            SqlSessionManager session =  SqlSessionManager.newInstance(resourceAsStream);
//            MapperProxyFactory mapperProxyFactory =  new MapperProxyFactory(UserDao.class);
//            UserDao mapper = (UserDao) mapperProxyFactory.newInstance(session);
            UserDao mapper = (UserDao)  Proxy.newProxyInstance(
                    UserDao.class.getClassLoader(),
                    new Class[] { UserDao.class },
                    new MapperProxy<UserDao>(session, UserDao.class,new ConcurrentHashMap<Method, MapperMethod>()));

            User user = mapper.selectByUser(new User(1,null),1);
//            User user = mapper.selectById( 1);
            System.out.println(user.getName());

            session.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void b (){
        try {
            //读取mybatis-config.xml文件
            InputStream resourceAsStream = Resources.getResourceAsStream("MapperConfig.xml");
            //初始化mybatis,创建SqlSessionFactory类的实例
            SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建session实例
            SqlSession session = sqlSessionFactory.openSession();

            UserDao mapper = session.getMapper(UserDao.class);
//            User user = mapper.selectById();
//            System.out.println(user.getName());

            User user = new User();
            user.setName("2222222");
            int insert = mapper.insert(user);
            System.out.println(insert);
            session.commit();
            //关闭session
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
